<?php
namespace app\lib\dou;

class DouTool
{

    static private $instance = null;

    private $app_key;

    private $app_secret;

    public  function __construct()
    {
        $this->app_key = config("dou.app_key");
        $this->app_secret = config("dou.app_secret");

    }

    public static function getInstance(){
        if(!static::$instance){
            static::$instance = new static();
            return static::$instance;
        }
        return static::$instance;
    }

    public function turnArrToStr($param){
        if(!is_array($param)){
            return false;
        }

        ksort($param);
        $str = json_encode($param);
        return $str;
    }
    /*
     *  获取签名
     * */
    public function getSign($param,$method,$t){
        $str = $this->turnArrToStr($param);

        $sign = $this->app_secret."app_key".$this->app_key."method".$method.
            'param_json'.$str.'timestamp'.$t.'v2'.$this->app_secret;

        return md5($sign);
    }

    /*
     *  获取 access_token
     * */
    public function getAccessToken($param,$method){
        $t = date("Y-m-d H:i:s",time());
        $sign = $this->getSign($param,$method,$t);
        $str = $this->turnArrToStr($param);
        $params = [
            "app_key" => $this->app_key,
            "method" => $method,
            "param_json" => $str,
            "v" => 2,
            "sign" => $sign,
            "timestamp" => $t
        ];
        $url = "https://openapi-fxg.jinritemai.com/token/create?".http_build_query($params);

        $result = http_get($url);
        return $result;
    }
}